#pragma once

#include <QObject>
#include <QTcpSocket>
#include <QHostAddress>

#include <gameboycore/link_cable.h>

class TcpClient : public QObject
{
	Q_OBJECT

signals:
	void recieved(quint8);

public:
	TcpClient(QHostAddress addr, quint16 port, QObject* parent = nullptr) :
		QObject(parent),
		m_address(addr),
		m_port(port),
		m_socket(new QTcpSocket(this))
	{
		connect(m_socket, &QTcpSocket::disconnected, this, &TcpClient::disconnected);
		connect(m_socket, &QTcpSocket::readyRead, this, &TcpClient::readyRead);
		start();
	}

	virtual ~TcpClient() = default;

	void start()
	{
		m_socket->connectToHost(m_address, m_port);

		if (!m_socket->isOpen())
		{
			qDebug() << "TCP client could not bind";
		}
		else
		{
			qDebug() << "TCP client bound";
		}
	}

public slots:
	void readyRead()
	{
		QByteArray data = m_socket->readAll();

		auto byte = (quint8)data.at(0);

		emit recieved(byte);
	}

	void disconnected()
	{
		m_socket->deleteLater();
	}

	void linkReady(quint8 byte, gb::Link::Mode mode)
	{
		QByteArray data;
		data.append(byte);
		data.append(static_cast<quint8>(mode));

		m_socket->write(data);
	}

private:
	QTcpSocket* m_socket{ nullptr };
	QHostAddress m_address;
	quint16 m_port;
};
